package com.sinodata.bsm.cicp.collector.weblogic9;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.JmxUtil;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * <p>
 * Description: 
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-26 AM 10:07:17   liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class ServerSecurityCollector extends Collector {

    private static final Logger logger = Logger.getLogger(ServerSecurityCollector.class);

    private final HashMap invalidLogin = new HashMap();

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        String serversName = this.getParamMap().get("ServerSecurityName").trim();
        String port = this.getParamMap().get("port").trim();
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];

        String key = serversName + ":" + ip;
        long time = System.currentTimeMillis();
        ObjectName service;
        String name = null;
        Object attrValues[] = null;

        JMXConnector connector = null;
        MBeanServerConnection connection = null;
        try {
            connector = JmxUtil.getConnection(ip, Integer.parseInt(port));
            connection = connector.getMBeanServerConnection();
            service = new ObjectName("com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean");
            ObjectName[] serverRuntimes = (ObjectName[]) connection.getAttribute(service, "ServerRuntimes");
            String attributeNames[] = new String[] { "InvalidLoginAttemptsTotalCount", "InvalidLoginUsersHighCount", "LockedUsersCurrentCount", "LoginAttemptsWhileLockedTotalCount", "UnlockedUsersTotalCount", "UserLockoutTotalCount" };
            for (ObjectName objectName : serverRuntimes) {
                name = objectName.getKeyProperty("Name");
                if (!serversName.equals(name)) {
                    continue;
                } else {
                    Object t1 = connection.getAttribute(objectName, "ServerSecurityRuntime");
                    t1 = connection.getAttribute((ObjectName) t1, "DefaultRealmRuntime");
                    t1 = connection.getAttribute((ObjectName) t1, "UserLockoutManagerRuntime");
                    attrValues = JmxUtil.getAttribute(connection, (ObjectName) t1, attributeNames);
                    for (int i = 0; i < attrValues.length; i++) {
                        propValues[i] = ResPropertyValue.createPropValue(attrValues[i].toString(), propMetas[i]);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("failed to collect by ServerSecurityCollector", e);
            throw new CollectorException(e);
        } finally {
            JmxUtil.closeConnector(connector);
        }
        if (invalidLogin.get(key) != null) {
            String temp = String.valueOf(invalidLogin.get(key));
            String[] valueTime = temp.split(":");

            propValues[6] = ResPropertyValue.createPropValue(String.valueOf(((Long.parseLong(valueTime[0]) - Long.parseLong(attrValues[0].toString())) * 1000 * 60) / (time - Long.parseLong(valueTime[1]))), propMetas[6]);
            if (Long.parseLong(propValues[6].value) < 0) {
                propValues[6] = ResPropertyValue.createPropValue("0", propMetas[6]);
            }
        }
        invalidLogin.remove(key);
        invalidLogin.put(key, attrValues[0].toString() + ":" + String.valueOf(time));
        propertyValueX.setValues(propValues);
        values.add(propertyValueX);
        return values;
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "ServerSecurityName", "port" };
    }

    @Override
    public String[] getPropMeta() {
        // return new String[] { "InvalidLoginAttemptsTotalCount", "InvalidLoginUsersHighCount", "LockedUsersCurrentCount", "LoginAttemptsWhileLockedTotalCount", "UnlockedUsersTotalCount", "UserLockoutTotalCount", "tryCountms" };
        return new String[] { "$1", "$2", "$3", "$4", "$5", "$6", "$7" };
    }
}
